package com.handy.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.SocketChannel;

import org.apache.log4j.Logger;
public class Client {

	public static synchronized Client getInstance() {
		if (instance == null) {
			instance = new Client();
		}
		return instance;
	}

	public SocketChannel getClient() {
		SocketChannel client = null;

		if (null == getHostIp() || "".equals(getHostIp()) || getHostPort()==0){
			log.error("目标服务器的IP地址与端口必须设定！");
			return null;
		}
		
		try {
			log.debug("打开socket:"+getHostIp()+":"+getHostPort());
			client = SocketChannel.open();
			
			InetSocketAddress isa = null;
			
			//当指定本地ip时绑定本地ip
			if (null != getClientIp() && !"".equals(getClientIp())){
				int clientport = client.socket().getLocalPort();
				isa = new InetSocketAddress(getClientIp(), clientport);
				client.socket().bind(isa);//当本机有多个ip时可绑定指定的ip与port。
			}

			isa = new InetSocketAddress(getHostIp(), getHostPort());
			client.connect(isa);
			client.configureBlocking(false);
			if (log.isDebugEnabled()){
				log.info(client.socket().getLocalSocketAddress());
			}
		} catch (UnknownHostException e) {
			log.error(e.getMessage());
		} catch (IOException e) {
			log.error(e.getMessage());
		} 
		return client;
	}
	
	private static Logger log = Logger.getLogger(Client.class);

	private static Client instance = null;
	
	private String hostIp = "";
	private int hostPort = 0;
	private String clientIp = null;


	public String getHostIp() {
		return hostIp;
	}

	public void setHostIp(String hostIp) {
		this.hostIp = hostIp;
	}

	public int getHostPort() {
		return hostPort;
	}

	public void setHostPort(int hostPort) {
		this.hostPort = hostPort;
	}

	public String getClientIp() {
		return clientIp;
	}

	public void setClientIp(String clientIp) {
		this.clientIp = clientIp;
	}
	
}
